﻿using System;
using System.Windows.Navigation;

using Microsoft.Phone.Controls;

using NavigationCoercion.Actions;

namespace NavigationCoercion.Patterns
{
    internal class NavigatingPattern : INavigatingPattern
    {        
        private readonly string _page;
        private RedirectActionBase _action;
        private Func<bool> _condition;

        public NavigatingPattern(Type type)
        {
            this._page = type.GetPossibleXamlPagePath();            
        }

        public void RedirectWithReturnUri<T>(string paramKey)
        {
            this._action = new RedirectWithReturnUriAction(typeof(T), paramKey);
        }

        public INavigatingPattern If(Func<bool> condition)
        {
            this._condition = condition;

            return this;
        }

        public void RedirectTo<T>()
        {
            this._action = new RedirectAction(typeof(T));
        }

        internal bool TryApply(NavigatingCancelEventArgs e, PhoneApplicationFrame frame)
        {
            var currentUriStr = e.Uri.ToString();

            if (!(currentUriStr.StartsWith(this._page) && (this._condition == null || this._condition()))) 
                return false;

            e.Cancel = true;

            this._action.PerformRedirect(frame);

            return true;
        }
    }
}